// 一些工具函数
import Taro from "@tarojs/taro"
const QQMapWX = require('./qqmap-wx-jssdk.min.js')
import { QQ_MAP_KEY } from "../constants"
import uQRCode from './uqrcode'
export const checkoutLoginStatus = () => {
    // 本项目中以本地保存手机号且存在token字符串为判断标准
    const token = Taro.getStorageSync('token') || ''
    const phone = Taro.getStorageSync('userPhone') || ''

    if (token && phone) {
        return { token, phone }
    }

    return false
}


export const noOpenToast = () => {
    Taro.showToast({
        title: '暂未开放',
        icon: 'none'
    })
}

export const showToast = (info, icon) => {
    Taro.showToast({
        title: info,
        icon: icon
    })
}


export const getTimeDiff = (time1, time2) => {

    var difference = new Date(time1).getTime() - new Date(time2).getTime()

    if (difference > 0) {
        var seconds = Math.floor(difference / 1000);
        var minutes = Math.floor(seconds / 60);
        var hours = Math.floor(minutes / 60) || 0;

        minutes %= 60;
        seconds %= 60;

        return {
            difference, hours, minutes, seconds, isEqual: false
        }
    } else if (!difference) {
        return {
            isEqual: true
        }
    } else {
        return false;
    }

}

export const getTimeVal = (time1, time2) => {

    var difference = new Date(time1).getTime() - new Date(time2).getTime()

    var seconds = Math.floor(difference / 1000);
    var minutes = Math.floor(seconds / 60);
    var hours = Math.floor(minutes / 60) || 0;

    minutes %= 60;
    seconds %= 60;

    return {
        difference, hours, minutes, seconds, isEqual: false
    }

}

export const transformDate = (time) => {
    const date = new Date(time)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const min = date.getMinutes() + 1
    const sec = date.getSeconds()

    return {
        year, month, day, hour, min, sec
    }
}


export const queryStringToObject = (str) => {
    // 将字符串按 & 分割成数组
    const pairs = str.split('&');

    // 创建一个空对象来存储键值对
    const obj = {};

    // 遍历数组，将每个键值对分割并存储到对象中
    pairs.forEach(pair => {
        const [key, value] = pair.split('=');
        obj[key] = isNaN(value) ? value : parseInt(value); // 如果值是数字字符串，则转换成数字类型
    });

    return obj;
}

export const handleScan = (e) => {
    e.stopPropagation()
    Taro.scanCode({
        success: async (res) => {

            console.log(res)
            Taro.showToast({
                title: `扫码结果为:${res.scanType}-${res.result}`,
                icon: 'none'
            })
            // 在这里可以处理扫码成功后的逻辑  
            // 爬爬架任务的逻辑
            // if (res.result && res.result === 'CLIMB_START:ZXY') {
            //     // 确认是攀爬架任务 扫码开启，传递后台

            // }
            // 如果是扫道具补给站的小程序码
            // if (res.path && res.scanType === 'WX_CODE') {
            //     Taro.navigateTo({
            //         url: '/' + res.path
            //     })
            // }
        }
    })
}


export const testAuthSetting = (authType) => {
    return new Promise((resolve, reject) => {
        Taro.getSetting({
            success: function (res) {
                if (res.authSetting[`scope.${authType}`]) {
                    // 用户已授权获取用户信息的权限
                    resolve(true)
                } else {
                    // 用户未授权获取用户信息的权限
                    console.log('用户未授权获取用户信息的权限');
                    Taro.authorize({
                        scope: `scope.${authType}`,
                        success() {
                            // 用户同意授权
                            resolve(true)
                        },
                        fail() {
                            // 用户拒绝授权
                            resolve(false)
                        }
                    });
                }
            }
        })
    })
}
export const getLocation = () => {
    return new Promise(async (resolve, reject) => {
        const res = await testAuthSetting('userFuzzyLocation')
        if (res) {
            Taro.getFuzzyLocation({
                type: 'wgs84',
                success: async (res) => {
                    const { latitude, longitude } = res
                    const cityRes: any = await reverseAddressResolution(longitude, latitude)
                    console.log(cityRes, '123123')
                    if (cityRes) {
                        const { result } = cityRes
                        resolve(result)
                    }
                },
                fail: (err) => {
                    console.log(err)
                }
            })
        } else {
            reject(false)
        }
    })
}



export const switchTabUrl = (url: string) => {
    Taro.switchTab({
        url
    })
}

export const toPage = (url: string) => {
    Taro.navigateTo({
        url,
        fail(err) {
            console.log(err)
        }
    })
}


export const initQrCodeUrl = (canvasId, text) => {
    return new Promise((resolve, reject) => {
        uQRCode.make({
            canvasId: canvasId,
            text,
            size: 130,
            margin: 10,
            success: res => {
                console.log('r1e', res)
                resolve(res)
            },
            complete: (res) => {
                console.log('re', res)
            }
        })
    })
}


export const calculateMillisecondsUntilDeadline = (deadline) => {
    // 获取当前时间的时间戳
    const currentTime = new Date().getTime();

    // 获取截止日期的时间戳
    const deadlineTime = new Date(deadline).getTime();

    // 计算截止日期距离当前时间的毫秒数
    const millisecondsUntilDeadline = deadlineTime - currentTime;

    console.log(millisecondsUntilDeadline)
    return millisecondsUntilDeadline;
}


export const uploadFile = (file) => {
    return new Promise((resolve, reject) => {
        Taro.uploadFile({
            url: process.env.TARO_APP_API + 'upload',
            filePath: file,
            name: 'files',
            success: (res) => {
                const { data } = res
                resolve(data)
            },
            fail: (err) => {
                reject(err)
            }
        })
    })
}

export const batchUploadFiles = async (filePaths) => {
    const uploadTasks: any = [];

    // 遍历文件路径数组，逐个上传文件
    for (let i = 0; i < filePaths.length; i++) {
        const filePath = filePaths[i];

        // 调用 Taro.uploadFile 方法上传文件
        const uploadTask = Taro.uploadFile({
            url: process.env.TARO_APP_API + 'upload', // 上传文件的接口地址
            filePath: filePath.url,
            name: 'files', // 上传文件的字段名
        });

        uploadTasks.push(uploadTask);
    }

    // 等待所有文件上传任务完成
    const results = await Promise.all(uploadTasks);

    // 处理上传结果
    results.forEach((result, index) => {
        console.log(`文件 ${index + 1} 上传成功：`, result.data);
    });

    return results
}

export const handleNum = (data) => {
    if (!data || !data.length) return false
    let num = 0
    data.forEach(item => {
        num = num + item.num
    })
    return num
}


// 金额处理
export const addCommasToNumber = (amount) => {
    // 将金额数字转换为字符串，并按照小数点分割整数部分和小数部分
    let parts = amount.toString().split('.');
    // 整数部分
    let integerPart = parts[0];
    // 小数部分
    let decimalPart = parts[1] ? '.' + parts[1] : '';

    // 使用正则表达式将整数部分每三位添加一个逗号
    integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');

    // 返回添加逗号分隔的金额字符串
    return integerPart + decimalPart;
}

// 大写字母
export const getFirstLetterUpperCase = (word) => {
    // 使用正则表达式匹配单词的首字母
    let firstLetter = word.match(/\b\w/g)[0];
    // 将首字母转换为大写
    let firstLetterUpperCase = firstLetter.toUpperCase();
    // 返回大写的首字母
    return firstLetterUpperCase;
}

export const debounce = (func, delay) => {
    let timer;

    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(this, args);
        }, delay);
    };
}